from django.shortcuts import render

# Create your views here.
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from cart.models import Cart
from cart.serializers import CartSerializer, ReadCartSerializer
from rest_framework import status
from rest_framework import mixins
from rest_framework.viewsets import GenericViewSet
from cart.permissions import CartPermissions


class CartView(GenericViewSet,
               mixins.CreateModelMixin,
               mixins.ListModelMixin,
               mixins.DestroyModelMixin):
    """ 购物车相关接口 """

    queryset = Cart.objects.all()
    serializer_class = CartSerializer
    # 权限设置；用户登录之后才可以访问，且每个用户只能访问自己的数据【修改
    permission_classes = [IsAuthenticated, CartPermissions]

    def get_serializer_class(self):
        """ 实现读写数据 使用不同的序列化器 """
        if self.action == 'list':
            return ReadCartSerializer
        elif self.action == 'create':
            return self.serializer_class

    def create(self, request, *args, **kwargs):
        """ 添加商品到购物车 """
        user = request.user  # 获取登录的用户信息
        # 获取参数
        goods = request.data.get('goods')
        number = request.data.get('number', 1)
        # 校验该用户的购物车中是否有该商品
        if Cart.objects.filter(user=user.id, goods=goods).exists():
            # 成功查到，说明购物车里面已经有该商品【修改商品的数量
            cart_good = Cart.objects.get(user=user.id, goods=goods)  # 获取商品
            cart_good.number += number
            cart_good.save()
            # 对该商品使用序列化 返回数据
            serializer = self.get_serializer(cart_good)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            # 没有商品 就添加
            data = request.data
            data['user'] = user.id
            serializer = self.get_serializer(data=data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def list(self, request, *args, **kwargs):
        """ 查看当前用户的购物车的所有商品 """
        # 通过过滤用户id 查询和登录相同用户信息的商品
        queryset = self.get_queryset().filter(user=request.user)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def update_goods_status(self, request, *args, **kwargs):
        """ 修改商品的选中状态 """
        # 获取对象
        obj = self.get_object()
        # if obj.is_checked:
        #     obj.is_checked = False
        #     obj.save()
        # else:
        #     obj.is_checked = True
        #     obj.save()
        obj.is_checked = not obj.is_checked
        obj.save()

        return Response({'message': '修改成功'}, status=status.HTTP_200_OK)

    def update_goods_number(self, request, *args, **kwargs):
        """ 修改商品的数量 """
        # 获取参数
        number = request.data.get('number')
        if number == 0:
            number = -1  # 为0时, 0为假 下面判断过不了，所以修改为-1
        # 校验参数
        if not number:
            return Response({'error': '参数不能为空'}, status=status.HTTP_400_BAD_REQUEST)
        if not isinstance(number, int):
            return Response({'error': '参数类型错误'}, status=status.HTTP_400_BAD_REQUEST)
        # 获取对象
        obj = self.get_object()

        # 不能超过库存量
        if number > obj.goods.stock:
            return Response({'error': '超过该商品的库存，修改失败'}, status=status.HTTP_400_BAD_REQUEST)
        # 判断是否为小于等于0【删除
        elif number <= 0:
            # 删除该商品
            obj.delete()
            return Response({'message': '修改成功，该商品为0，以移除购物车'}, status=status.HTTP_200_OK)
        else:
            # 修改
            obj.number = int(number)
            obj.save()
            return Response({'message': '修改成功'}, status=status.HTTP_200_OK)
